// pages/settlement/index.js
const settlement = require("../controllers/ControllerX").controller.settlement;
const storeType = require("../controllers/ControllerX").controller.storeType;
const areaList = require("../controllers/ControllerX").controller.areaList;
const areaListChild = require("../controllers/ControllerX").controller.areaListChild;
const agent = require("../controllers/ControllerX").controller.agent;
const agentStaff = require("../controllers/ControllerX").controller.agentStaff;

const updateShopMsg = require("../controllers/Controller").controller.updateShopMsg;


const app = getApp({});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: "商户入驻申请",
    src1: " https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/image/my/img/my_but_15.png",
    src2: " https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/image/my/img/my_but_26.png",
    select_src: " https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/image/my/img/my_but_15.png",
    state: "1",
    select: false,
    multiIndex: ["00:00", "00:00"],
    hours: [
      ["00:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30", "05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:30"],
      ["24:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30", "05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:30"]
    ],
    selectOpen: false,
    selectState: 0,
    src3: " https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/image/settlement/img/settlement_down_icon_01.png",
    src4: " https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/image/settlement/img/settlement_close up_01.png",
    value: {
      rovinceName: "",
      cityName: "",
      districtName: "",
      districtId: '',
      agentStaffId: '',
      agentId: '',
      typeId: null,
      label: "",
      shopName: "",
      address: "",
      adminName: "",
      mobile: "",
      customer: "",
      detail: "",
      businessTime: "",
      shopImg: "",
      idImg: "",
      idBackImg: "",
      businessImg: "",
      lng: "",
      lat: "",
      internalImgs: ""
    },
    //地区
    selectCity: "",
    addressDetail: "",
    storeType: [

    ],
    selectStoreName: '',
    token: '',
    idx: [0, 0, 0], // 多列选择结果的索引号列表
    list: [
      // 用于picker第一列的数据源
      [

      ],
      // 用于picker第二列的数据源
      [

      ],
      // 用于picker第三列的数据源
      [

      ]
    ], // 用于渲染UI
    shen: "",
    shi: "",
    qu: "",
    quId: "",
    imgList: [],
    imgList2: [],
    baseUrl: "https://www.xlshhr.com/beauty-industry",
    agentName: "",
    agentShow: false,
    bottom: 0,
    settlementType: '',
    isFast: true,
    isReplenish: true,
    isSettle: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取保存的信息
    const applicationMsg=wx.getStorageSync("applicationMsg")
    if(applicationMsg){
      let {value,imgList,imgList2,selectStoreName} =JSON.parse(applicationMsg) 
      this.setData({
        value,
        imgList:imgList||[],
        imgList2:imgList2||[],
        selectStoreName
      })
    }

    this.setData({
      token: wx.getStorageSync("token")
    })
    if (options.isReplenish) {
      this.setData({
        isFast: false,
        title: "完善店铺信息"
      })
    }

    //获取扫码参数
    if (options.scene) {

      this.setData({
        agentShow: true
      })
      let scene = decodeURIComponent(options.scene);
      let [type, id, settlementType] = scene.split(",");
      if (settlementType == 1) {
        this.setData({
          settlementType,
          isReplenish: false
        })
      }
      if (type == "AG") {
        //获取代理商信息
        agent({
          agentId: id
        }).then(res => {
          let data = res.data;
          this.setData({
            agentName: data.agentName,
            'value.agentId': data.id
          })
        })
      } else {
        //获取代理商员工信息
        agentStaff({
          agentStaffId: id
        }).then(res => {
          let data = res.data;
          this.setData({
            agentName: data.agentName,
            'value.agentStaffId': data.id
          })
        })
      }
    }
  },
  onUnload() {
    // 保存信息
    if (this.data.isSettle) return
    let applicationMsg = {
      value: this.data.value,
      imgList: this.data.imgList,
      imgList2: this.data.imgList2,
      selectStoreName: this.data.selectStoreName,
    }
    applicationMsg=JSON.stringify(applicationMsg)
    wx.setStorageSync('applicationMsg', applicationMsg)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getStoreType();
    this.mapState();
    this.getAreaList();

    //获取标签页返回的数据
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1]; //当前页面
    let str = currPage.data.mydata;
    if (!str) return
    console.log(str) //为传过来的值
    this.setData({
      'value.label': str
    })


  },

  // 点击选中
  access(event) {
    let state = event.currentTarget.dataset.state;
    if (state == "1") {
      this.setData({
        select_src: this.data.src2,
        state: "0",
        select: true
      })
    } else {
      this.setData({
        select_src: this.data.src1,
        state: "1",
        select: false
      })
    }
  },
  //时间选中
  bindChange(e) {
    let val = e.detail.value
    console.log(val);
  },
  jumpToAgreement() {
    wx.navigateTo({
      url: '/pages/settlement/agreement/index',
    })
  },
  //打开或收回下拉框
  openselect() {
    if (this.data.selectState == 0) {
      this.setData({
        selectOpen: true,
        selectState: 1
      })
    } else {
      this.setData({
        selectOpen: false,
        selectState: 0
      })
    }
  },


  /**************************************** */
  // 进行入驻操作
  doSettlement() {
    let internalImgs = this.data.imgList.join();
    this.setData({
      'value.internalImgs': internalImgs
    })
    let businessImg = this.data.imgList2.join();
    this.setData({
      'value.businessImg': businessImg
    })
    if (this.data.state == 1 && this.data.isFast) {
      wx.showToast({
        icon: "none",
        title: '请勾选入驻申请协议',
        duration: 1500
      })
      return
    }

    let value = this.data.value;
    let isFast = this.data.isFast;
    let isReplenish = this.data.isReplenish;
    let fastSettle = !value.typeId || !value.shopName || !value.adminName || !value.mobile || !value.businessTime
    let replenishMsg = !value.rovinceName || !value.cityName || !value.districtName || !value.address || !value.customer || !value.shopImg || !value.idImg || !value.idBackImg || !value.businessImg

    //判断是否成功获取经纬度
    if (isFast && (!value.lng || !value.lat)) {
      let that=this
      wx.showModal({
        title: '需打开定位获取位置信息',
        confirmText: '去打开',
        success (res) {
          if (res.confirm) {
            wx.openSetting({
              success(res) {
               that.mapState()
              }
            })
          }
        }
      })
      
      return
    }

    if (!value.label) {
      value.label = '其他'
    }

    // 完善店铺信息
    if (isReplenish && !isFast) {
      if (replenishMsg) {
        wx.showToast({
          icon: "none",
          title: '请完善信息',
        })
      } else {
        let reValue = {
          shopId: wx.getStorageSync('shopId'),
          rovinceName: value.rovinceName,
          cityName: value.cityName,
          districtName: value.districtName,
          districtId: value.districtId,
          label: value.label,
          address: value.address,
          customer: value.customer,
          detail: value.detail,
          shopImg: value.shopImg,
          idImg: value.idImg,
          idBackImg: value.idBackImg,
          businessImg: value.businessImg,
          lng: value.lng,
          lat: value.lat,
          internalImgs: value.internalImgs
        }
        
        updateShopMsg(reValue).then(res => {
          wx.showToast({
            title: '操作成功',
          })
          wx.removeStorageSync('applicationMsg')
          this.setData({
            isSettle: true
          })
          setTimeout(function () {
            wx.navigateBack()
          }, 1000)
        })
      console.log(reValue);
      }
      return
    }
    // 快速入驻
    if (isFast && !isReplenish) {
      value = {
        settlementType: 1,
        typeId: value.typeId,
        mobile: value.mobile,
        agentStaffId: value.agentStaffId,
        agentId: value.agentId,
        shopName: value.shopName,
        adminName: value.adminName,
        businessTime: value.businessTime,
      }
      if (fastSettle) {
        wx.showToast({
          icon: "none",
          title: '请完善信息',
        })
        return
      }
    }
    // 普通入驻
    if (isFast && isReplenish) {
      if (fastSettle || replenishMsg) {
        wx.showToast({
          icon: "none",
          title: '请完善信息',
        })
        return
      }
    }
    
    settlement(value).then(res => {
      if (res.code == 1) {
        wx.showToast({
          title: '入驻申请已提交',
          icon: 'success',
          duration: 1000
        })
        wx.removeStorageSync('applicationMsg')
        this.setData({
          isSettle: true
        })
        setTimeout(function () {
          wx.redirectTo({
            url: '/pages/login/index',
          })
        }, 1000)
      }
    })
    console.log(value);
  },


  //选中店铺类型
  selectStoreType(e) {
    let typeId = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;
    this.setData({
      'value.typeId': typeId,
      selectStoreName: name,
      selectOpen: false
    })
  },
  //跳转行业标签
  jumpTags() {
    wx.navigateTo({
      url: '/pages/settlement/tags/index',
    })
  },

  //输入门店名称
  getStoreName(e) {
    let value = e.detail.value;
    this.setData({
      'value.shopName': value
    })
    console.log(this.data.value.shopName)
  },

  //输入详细地址
  getAddressDetail(e) {
    let value = e.detail.value;
    this.setData({
      addressDetail: value
    })
    this.setData({
      'value.address': this.data.selectCity + this.data.addressDetail
    })
    console.log(this.data.value.address);
  },
  //输入负责人
  getPersonName(e) {
    let value = e.detail.value;
    this.setData({
      'value.adminName': value
    })
    console.log(this.data.value.adminName)
  },

  //输入联系电话
  getMobile(e) {
    let value = e.detail.value;
    this.setData({
      'value.mobile': value
    })
    console.log(this.data.value.mobile)
  },

  //输入客服热线
  getHotMobile(e) {
    let value = e.detail.value;
    this.setData({
      'value.customer': value
    })
    console.log(this.data.value.customer)
  },
  //选择营业时间
  selectTime(e) {
    let startArr = e.detail.value[0];
    let endArr = e.detail.value[1];
    let startTime = this.data.hours[0][startArr];
    let endTime = this.data.hours[1][endArr];
    this.setData({
      'value.businessTime': startTime + "-" + endTime
    })
    console.log(this.data.value.businessTime);
  },
  //输入门店介绍
  inputText(e) {
    let value = e.detail.value;
    this.setData({
      'value.detail': value
    })
    console.log(this.data.value.detail)
  },

  //获取店铺类型
  getStoreType() {
    storeType().then(res => {
      this.setData({
        storeType: res.data
      })
      console.log(this.data.storeType)
    })
  },


  //判断地理位置是否授权并授权
  mapState() {
    let that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation'] || res.authSetting['scope.userLocation'] == false) {
          console.log(res);
          wx.authorize({
            scope: 'scope.userLocation',
            success(res) {
              console.log(res);
              wx.getLocation({
                type: 'wgs84',
                isHighAccuracy: true,
                success(res) {
                  that.setData({
                    'value.lng': res.longitude,
                    'value.lat': res.latitude
                  })
                }
              })
            }
          })
        } else {
          wx.getLocation({
            type: 'wgs84',
            isHighAccuracy: true,
            success(res) {
              console.log(res);
              // console.log(res.latitude);
              // console.log(res.longitude);
              that.setData({
                'value.lng': res.longitude,
                'value.lat': res.latitude
              })
            }
          })
        }
      }
    })
  },

  //门店图片上传
  uploadImg1() {
    let that = this;
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          url: that.data.baseUrl + '/api/img/uploadFile',
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            'sessionId': that.data.token
          },
          success(res) {
            console.log(res);
            // const data = res.date
            let src = JSON.parse(res.data)
            that.setData({
              'value.shopImg': src.data
            })
          }
        })
      }
    })
  },

  //内部环境图片上传
  uploadImg2() {
    let list = this.data.imgList;
    if (list.length < 9) {
      let that = this;
      wx.chooseImage({
        success(res) {
          const tempFilePaths = res.tempFilePaths;
          const tempFiles = res.tempFiles;
          for (let i = 0; i < 9 - that.data.imgList.length; i++) {
            wx.uploadFile({
              url: that.data.baseUrl + '/api/img/uploadFile',
              filePath: tempFilePaths[i],
              name: 'image',
              formData: {
                'sessionId': that.data.token
              },
              success(res) {
                console.log(res);
                // const data = res.date
                let src = JSON.parse(res.data)
                list.push(src.data);
                that.setData({
                  'imgList': list
                })
              }
            })
          }
        }
      })
    }
  },

  //身份证正面上传
  uploadImg3() {
    let that = this;
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: that.data.baseUrl + '/api/img/uploadFile',
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            'sessionId': that.data.token
          },
          success(res) {
            console.log(res);
            // const data = res.date
            let src = JSON.parse(res.data)
            that.setData({
              'value.idImg': src.data
            })
          }
        })
      }
    })
  },

  //身份证背面上传
  uploadImg4() {
    let that = this;
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: that.data.baseUrl + '/api/img/uploadFile',
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            'sessionId': that.data.token
          },
          success(res) {
            console.log(res);
            // const data = res.date
            let src = JSON.parse(res.data)
            that.setData({
              'value.idBackImg': src.data
            })
          }
        })
      }
    })
  },

  //营业执照上传
  uploadImg5() {
    let list = this.data.imgList2;
    if (list.length < 5) {
      let that = this;
      wx.chooseImage({
        success(res) {
          const tempFilePaths = res.tempFilePaths;
          const tempFiles = res.tempFiles;
          // if(tempFiles[0].size>1024*1024){
          //   wx.showToast({
          //     title: '单张图片大不能超过1MB',
          //     icon: 'none',
          //     duration: 2000
          //   })
          //   return
          // }
          for (let i = 0; i < 5 - that.data.imgList2.length; i++) {
            wx.uploadFile({
              url: that.data.baseUrl + '/api/img/uploadFile',
              filePath: tempFilePaths[i],
              name: 'image',
              formData: {
                'sessionId': that.data.token
              },
              success(res) {
                console.log(res);
                // const data = res.date
                let src = JSON.parse(res.data)
                list.push(src.data);
                that.setData({
                  imgList2: list
                })
              }
            })
          }
        }
      })
    }
  },

  //图片上传
  /************************************ */

  chooseImg() {
    let that = this;
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: 'http://111.230.226.223:80/beauty-industry/api/img/uploadFile',
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'sessionId': that.data.token
          },
          success(res) {
            const data = res.data
            that.setData({
              'value.shopImg': res.data.data
            })
          }
        })
      }
    })
  },

  //获取省
  getAreaList() {
    areaList({
      leveltype: 1
    }).then(res => {
      let shen = res.data;
      let id = 0;
      let shenList = "list[" + id + "]"
      this.setData({
        [shenList]: shen,
        shen: shen[0].name
      })
      this.getAreaListChildShi(res.data[0].id)
    })
  },

  //根据上层id获取市
  getAreaListChildShi(id) {
    areaListChild({
      areaId: id
    }).then(res => {
      let shi = res.data;
      let id = 1;
      let shiList = "list[" + id + "]"
      this.setData({
        [shiList]: shi,
        shi: shi[0].name
      })
      this.getAreaListChildQu(res.data[0].id)
    })
  },

  //根据上层id获取区
  getAreaListChildQu(id) {
    areaListChild({
      areaId: id
    }).then(res => {
      let qu = res.data;
      let id = 2;
      let quList = "list[" + id + "]"
      this.setData({
        [quList]: qu,
        qu: qu[0].name,
        quId: qu[0].id
      })
    })
  },
  change(e) {
    this.setData({
      'value.rovinceName': this.data.shen,
      'value.cityName': this.data.shi,
      'value.districtName': this.data.qu,
      'value.districtId': this.data.quId
    })
    console.log(this.data.value);
  },
  columnChange(e) {
    let column = e.detail.column; //列
    let value = e.detail.value; //行

    let id = this.data.list[column][value].id;
    if (column == 0) {
      this.setData({
        shen: this.data.list[column][value].name
      })
      this.getAreaListChildShi(id);
    } else if (column == 1) {
      this.setData({
        shi: this.data.list[column][value].name
      })
      this.getAreaListChildQu(id);
    } else {
      this.setData({
        qu: this.data.list[column][value].name,
        quId: this.data.list[column][value].id
      })
    }
  },

  //跳转裁剪页
  jumpTowecropper() {
    var _this = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths[0];
        wx.navigateTo({
          url: '/pages/settlement/imgcorp/index?img=' + tempFilePaths,
        });
      }
    })
  },
  uploadImage(path) {
    var that = this;
    wx.uploadFile({
      url: that.data.baseUrl + '/api/img/uploadFile',
      filePath: path,
      name: 'image',
      formData: {
        'sessionId': that.data.token
      },
      success(res) {
        console.log(res);
        // const data = res.date
        let src = JSON.parse(res.data)
        that.setData({
          'value.shopImg': src.data
        })
      }
    })
  },

  //输入适配
  inputFocus(e) {
    let that = this;
    that.setData({
      bottom: e.detail.height
    })
  },
  inputBlue() {
    let that = this;
    that.setData({
      bottom: 0
    })
  },

  //跳转地图选择
  getMap() {
    let that = this
    wx.chooseLocation({
      latitude: that.data.value.lat ? that.data.value.lat : '',
      longitude: that.data.value.lng ? that.data.value.lng : '',
      success(e) {
        console.log(e)
        that.setData({
          'value.lat': e.latitude,
          'value.lng': e.longitude,
          'value.address': e.name
        })
      }
    })
  }
})